%# Copyright (c) 2025 Huawei Device Co., Ltd.
%# Licensed under the Apache License, Version 2.0 (the "License");
%# you may not use this file except in compliance with the License.
%# You may obtain a copy of the License at
%#
%# http://www.apache.org/licenses/LICENSE-2.0
%#
%# Unless required by applicable law or agreed to in writing, software
%# distributed under the License is distributed on an "AS IS" BASIS,
%# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%# See the License for the specific language governing permissions and
%# limitations under the License.
%#
%
% require_relative 'Array_code'

% TemplateData::get_lambda_data.each { |lambda_args_params|
%   lambda_params_num, lambda_args, lambda_params = lambda_args_params

/**
 * Calls a defined callback function on each element of an array, and returns an array that contains the results.
 *
 * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
 *
 * @returns `Array` instance, constructed from `this` and given function.
 */
<%= access_public %> <%= override %> map<%= map_generic %>(<%= this_arg %>callbackfn: (value: <%= el_type %><%= lambda_params %>) => <%= mapped_type %>): <%= array_of_type.(mapped_type) %> {
    const len = <%= this_len_int %>;
    let res : <%= make_fixed_array %> = <%= make_buffer.('len', mapped_type) %>;
    for (let i = 0; i < len; i++) {
        res[i] = callbackfn(<%= get_unsafe.(this, 'i') %><%= lambda_args %>);
    }
    return <%= from_buffer.('res', mapped_type) %>;
}

/**
 * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
 *
 * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
 *
 * @returns a result after applying callbackfn over all elements of the Array
 */
<%= access_public %> <%= override %> reduceRight<%= this_generic %>(<%= this_arg %>callbackfn: (previousValue: <%= el_type %>, currentValue: <%= el_type %><%= lambda_params %>) => <%= el_type %>): <%= el_type %> {
    if (<%= this_len_int %> == 0) {
        throw new TypeError("Reduce of empty array with no initial value")
    }
    let acc: <%= el_type %> = <%= get_unsafe.(this, "#{this_len_int} - 1") %>;
    for (let i = <%= this_len_int %> - 2; i >= 0; i--) {
        acc = callbackfn(acc, <%= get_unsafe.(this, 'i') %><%= lambda_args %>)
    }
    return acc
}
% }
